<template>
    <div class="elemeter">
        <Tabs type="card" :animated="false" @on-click="changeTab">
            <TabPane label="电表信息" name="detail" id="padding15">
                <Card class="elemeter-base" dis-hover :padding='0'>
                    <p slot='title'>
                        基本信息
                    </p>

                    <a slot="extra">
                        <Button v-pmis="26" type='ghost' class='yd-button' @click="isShowMaxPower = true" v-if="isShowMaxPowerBtn">超功率设置</Button>
                        <Button v-pmis="26" type='ghost' class='yd-button' @click='synData'>电表同步</Button>
                        <Button v-pmis="26" type='ghost' class='yd-button' :loading="isLoading" v-if='elemeter_info.enable_state != 2' @click='elemeterOff'>电表断电</Button>
                        <Button v-pmis="26" type='ghost' class='yd-button' :loading="isLoading" v-if='elemeter_info.enable_state == 2' @click='elemeterOn'>电表通电</Button>
                        <Button v-pmis="26" type='ghost' class='yd-button' @click='clear = true' v-if="elemeter_info.hardware_info && elemeter_info.hardware_info.sn.substring(6, 8) != '05' && elemeter_info.hardware_info.sn.substring(6, 8) != '11' && elemeter_info.hardware_info.sn.substring(6, 8) != '12' && elemeter_info.hardware_info.sn.substring(6, 8) != '06'">电表清零</Button>
                    </a>

                    <Row class='elemeter-base-row'>
                        <Col span='6' class='elemeter-base-row-item'>
                            <Row type='flex' align='middle' class='elemeter-base-row-item-line'>
                                <strong>基本信息</strong>
                            </Row>
                            <Row class='elemeter-base-row-item-line'>
                                <i>名称：</i>
                                <Input style='width:50%' v-model='elemeter_name' :readonly='edit'></Input>
                                <Button type='ghost' class="margin-left-10 yd-button" v-show='edit==true' @click='edit=!edit' v-pmis="23">修改</Button>
                                <Button v-pmis="23" class="margin-left-10 yd-button" v-show='edit==false' @click='ok'>保存</Button>
                            </Row>
                            <Row class='elemeter-base-row-item-line'>
                                <i>序列号:</i>
                                {{elemeter_info.hardware_info?elemeter_info.hardware_info['sn']:''}}
                            </Row>
                            <Row class='elemeter-base-row-item-line' v-if="elemeter_info.lqi >= 0">
                                <i>信号强度:</i>
                                {{elemeter_info.lqi}}
                            </Row>
                            <Row class='elemeter-base-row-item-line'>
                                <i>uuid：</i>
                                {{elemeter_info.uuid}}
                            </Row>
                            <Row class='elemeter-base-row-item-line'>
                                <i>最大功率：</i>
                                {{elemeter_info.capacity}} Kw
                            </Row>
                            <Row class='elemeter-base-row-item-line'>
                                <i>状态：</i>
                                <span class="margin-right-10">{{elemeter_info.onoff_line == 1?'在线':'离线'}}</span>（更新时间:{{elemeter_info.onoff_time | dateFrm}}）
                            </Row>
                            <Row class='elemeter-base-row-item-line'>
                                <i>型号：</i>
                                {{elemeter_info.type || '-'}}
                            </Row>
                            <Row class='elemeter-base-row-item-line'>
                                <i>绑定时间：</i>
                                {{elemeter_info.bind_time | dateFrm}}
                            </Row>
                            <Row class='elemeter-base-row-item-line' v-if='elemeter_info.elecollector'>
                                <i>绑定采集器：</i>
                                {{elemeter_info.elecollector?elemeter_info.elecollector['description']:'暂无'}}
                            </Row>
                            <Row class='elemeter-base-row-item-line' v-if='elemeter_info.gateway'>
                                <i>绑定网关：</i>
                                {{elemeter_info.gateway?elemeter_info.gateway['description']:'暂无'}}
                            </Row>
                        </Col>

                        <Col span='6' class='elemeter-base-row-item'>
                            <Row type='flex' align='middle' class='elemeter-base-row-item-line'>
                                <strong>保修信息</strong>
                            </Row>
                            <Row class='elemeter-base-row-item-line'>
                                <strong>保修起始时间：</strong>
                                {{elemeter_info.guarantee_begin}}
                            </Row>
                            <Row class='elemeter-base-row-item-line'>
                                <strong>保修截止时间：</strong>
                                {{elemeter_info.guarantee_end}}
                            </Row>
                        </Col>

                        <Col span='6'>
                            <Row type='flex' align='middle' class='elemeter-base-row-item-line'>
                                <strong>用电信息</strong>
                            </Row>

                            <Row class='elemeter-base-row-item-line'>
                                <i>当前用电：</i>
                                {{elemeter_info.consume_amount}}度
                                （更新时间:{{ elemeter_info.consume_amount_time | dateFrm}}）
                            </Row>

                            <!-- <Row 
                            class='elemeter-base-row-item-line' 
                            v-if="room_info && room_info.pay_type == 1 && elemeter_info.hardware_info && elemeter_info.hardware_info.sn.substring(6, 8) != '05' && elemeter_info.hardware_info.sn.substring(6, 8) != '11' && elemeter_info.hardware_info.sn.substring(6, 8) != '12' && elemeter_info.hardware_info.sn.substring(6, 8) != '06'">
                                <strong>剩余电量：</strong>
                                {{ (elemeter_info.power_total - elemeter_info.consume_amount).toFixed(2) }}度
                                （更新时间:{{ Math.max(elemeter_info.consume_amount_time, elemeter_info.power_total_time) | dateFrm}}）
                            </Row> -->

                            <Row class='elemeter-base-row-item-line'>
                                <i>电表状态：</i>
                                {{elemeter_info.enable_state == 2 ? '断电':'通电'}}
                            </Row>

                            <Row class='elemeter-base-row-item-line'>
                                <strong>跳闸阈值：</strong>
                                <span v-if="isPayFirst">
                                    {{thresholdValue(room_info.electric_amount, room_info.overdraft_amount)}}度
                                </span>
                                <span v-else>-</span>
                            </Row>

                            <Row class='elemeter-base-row-item-line'>
                                <strong>透支额度：</strong>
                                <span v-if="isPayFirst">
                                    {{room_info.overdraft_amount | amountFrm}}度
                                </span>
                                <span v-else>-</span>
                            </Row>
                        </Col>

                        <Col span='6' class='elemeter-base-row-right-item' v-if="isShowTitle">
                            <Row type='flex' align='middle' class='elemeter-base-row-item-line' >
                                <strong>硬件信息</strong>
                            </Row>

                            <Row class='elemeter-base-row-item-line' :key="index" v-if="elemeter_info.hardware_info.versions[item.key]" v-for="(item, index) in versions_keys">
                                <strong>{{item.name}}</strong>
                                {{elemeter_info.hardware_info.versions[item.key]}}
                            </Row>
                        </Col>
                    </Row>
                </Card>

                <!-- 电表设置最大功率弹窗 -->
                <Modal v-model="isShowMaxPower" title="设置最大功率">
                    <Input v-model="maxPower" :placeholder="Tip" style="width: 100%" />
                    <p style="margin-top: 10px">总功率超过设定的最大用电功率，停止供电</p>

                    <div slot="footer">
                        <Button type="text" @click='isShowMaxPower = false'>取消</Button>
                        <Button type="primary" @click="saveMaxPower">保存</Button>
                    </div>
                </Modal>


                <Modal v-model="clear" title="电表清零">
                    <div>
                        <div>
                            <P style='text-align: left'>您将针对以下内容清零:</P>
                            <P style='text-align: left'>（1）电表屏显用电读数；</P>
                            <P style='text-align: left'>（2）房间总用电量；</P>
                            <P style='text-align: left'>（3）剩余电量 (预付费模式)</P>
                        </div>
                    </div>
                    <P style='text-align: left'>注：</P>
                    <P style='text-align: left'>（1）电表清零后，历史记录请在报表中核查；</P>
                        <p>（2）该操作将记录在日志中；</P>
                    <div slot="footer">
                        <Button type="text" @click='clear = false'>取消</Button>
                        <Button type="primary" @click='elemeterReset()'>保存</Button>
                    </div>
                </Modal>
            </TabPane>
            <TabPane 
                label="关联设备" 
                name="correlation" 
                style="min-height:550px"
                v-if="elemeter_info.device_ability && (elemeter_info.device_ability.indexOf('GW') > -1 || elemeter_info.device_ability.indexOf('ELEC') > -1)">
                <correlation :room="room" :correlationDevice="elemeter_info.device_ability.indexOf('ELEC') > -1 ? 'elecollector' : 'gateway'" v-if="activeName == 'correlation'"></correlation>
            </TabPane>
            <TabPane label="屏显读数" name="eleWater" id="padding15">
                <eleWaterRecord :room="room" :recordType="0" @on-elemeter-left='elemeterLeft' v-if="activeName == 'eleWater'"></eleWaterRecord>
            </TabPane>
            <TabPane label="操作记录" name="operate"  id="padding15" style="min-height:550px;">
                <roomOperate :room="room" :operateType="'elemeter'" v-if="activeName == 'operate'"></roomOperate>
            </TabPane>
            <TabPane label="异常记录" name="unnormal" style="min-height:550px;" id="padding15">
                <roomUnnormal :room="room" :unnormalType="'ELEMETER'" v-if="activeName == 'unnormal'"></roomUnnormal>
            </TabPane>
            <TabPane label="第三方接口调用记录" name="openapi-log">
                <openapi-log v-if="loadedComponent.includes('openapi-log')" device-type="elemeter" :device-id="room.id" :room-id="room.roomId"></openapi-log>
            </TabPane>
        </Tabs>
    </div>
</template>
<script>
// import util from '@/libs/util';
import { http, api } from '@/libs/http'
import dayjs from 'dayjs'
import roomUnnormal from './roomUnnormal'
import eleWaterRecord from './eleWaterRecord'
import roomOperate from './roomOperate'
import correlation from './correlation'
import { refreshRoom } from './room-list/util'
import openapiLog from '../log/openapi-log'

export default {
  name: 'elemeter',
  props: {
    room: Object,
    homeId: Number
  },
  components: {
    roomUnnormal,
    eleWaterRecord,
    roomOperate,
    correlation,
    openapiLog
  },
  created () {
    this.elemeter_name = this.room.description
    this.elemeter_info = this.room
    this.get_room_detail()
  },
  data () {
    return {
      loadedComponent: [],
      maxPower: '', // 最大功率
      isShowMaxPower: false, // 是否设置最大功率
      room_info: null,
      isLoading: false,
      activeName: 'detail',
      clear: false,
      edit: true,
      elemeter_name: '',
      elemeter_left: '',
      partition: false,
      elemeter_switch: null,
      elemeter_info: '',
      maxPowerValue: null,
      data6: [],
      data5: [],
      versions_keys: [ // 版本key
        {
          key: 'app_version',
          name: '固件版本：'
        },
        {
          key: 'hardware_version',
          name: '硬件版本：'
        },
        {
          key: 'protocol_version',
          name: '协议版本：'
        },
        {
          key: 'zigbee_version',
          name: 'ZigBee版本：'
        }
      ]
    }
  },
  methods: {
    /**
        * 设置最大功率
        */
    saveMaxPower () {
      const maxPower = Number(this.maxPower)

      if (!isNaN(maxPower) && maxPower >= 1 && this.maxPowerValue && maxPower <= this.maxPowerValue) {
        const { roomId, id } = this.room // 历史遗留问题 room其实是device信息

        http.request(this, api.elemeters_capacity_set, [roomId, id], { capacity: maxPower }, (res, err) => {
          if (!res || err) {
            return
          }

          this.$Message.success('最大功率设置成功')
          this.maxPower = ''
          this.isShowMaxPower = false
        })
      } else {
        this.$Message.error('请按照提示输入合理的功率数值')
      }
    },

    thresholdValue (electricAmount, overdraftAmount) {
      return (Number(electricAmount) + Number(overdraftAmount)).toFixed(2)
    },
    changeTab (name) {
      this.activeName = name
      if (name === 'detail') {
        // 切换回来电表详情之后重新刷新数据
        // this.get_room_detail()
        this.getData()
      }
      if (!this.loadedComponent.includes(name)) this.loadedComponent.push(name)
    },
    get_room_detail () {
      http.request(this, api.room_info, [this.room.roomId], null, (res, err) => {
        if (!res || err) {
          return
        }

        this.room_info = res
      })
    },
    elemeterReset () {
      this.clear = false
      let room = this.elemeter_info
      http.request(this, api.elemeter_reset, [room.roomId, room.id], null, (res, err) => {
        if (!res || err) {
          return
        }
        this.$store.commit('refresh_elemeter', Math.random())
        this.$Message.success('清零成功')
      })
    },

    synData () {
      const params = {
        uuid: this.elemeter_info.uuid
      }
      http.request(this, api.room_elemeter_sync, [this.room.roomId, this.elemeter_info.id], params, (res, err) => {
        if (!res || err) {
          return
        }
        this.$Message.success('指令成功发送，等待设备响应')
      })
    },
    get_elemeter_switch_state (roomId, id) {
      this.isLoading = true
      let timeoutStart = new Date().getTime()
      let timer = setInterval(() => {
        let diffTime = new Date().getTime() - timeoutStart
        if (diffTime > 180000) {
          clearInterval(timer)
        }
        http.request(this, api.elemeter_info, [roomId, id], null, (res, err) => {
          if (!res || err) {
            return
          }
          // console.log('res', res.switch_stage)
          if (diffTime > 175000) {
            this.$Message.warning('操作失败')
            this.isLoading = false
          }

          if (res.switch_stage === 2) {
            clearInterval(timer)
            this.$Message.warning('操作失败')
            this.isLoading = false
          } else if (res.switch_stage === 3) {
            clearInterval(timer)
            this.$Message.success('操作成功')
            this.isLoading = false
            this.getData()
          }
        })
      }, 3000)
    },
    elemeterOff () {
      this.$Modal.confirm({
        width: '300px',
        content: '确定进行断电操作?',
        onOk: () => {
          let room = this.room
          http.request(this, api.elemeter_close, [room.roomId, room.id], null, (res, err) => {
            if (!res || err) {
              return
            }
            this.$Message.success('已发送断电请求，请稍后')
            this.get_elemeter_switch_state(room.roomId, room.id)
          })
        }
      })
    },
    elemeterOn () {
      this.$Modal.confirm({
        width: '300px',
        content: '确定进行通电操作?',
        onOk: () => {
          let room = this.room
          http.request(this, api.elemeter_open, [room.roomId, room.id], null, (res, err) => {
            if (!res || err) {
              return
            }
            this.$Message.success('已发送通电请求，请稍后')
            this.get_elemeter_switch_state(room.roomId, room.id)
          })
        }
      })
    },
    ok () {
      this.edit = !this.edit
      let room = this.room
      http.request(this, api.device_update, [room.roomId, room.id], { description: this.elemeter_name }, (res, err) => {
        if (!res || err) {
          this.elemeter_name = this.room.description
          return
        }
        this.$Message.success('修改成功')
        refreshRoom(this.homeId, this.room.roomId)
      })
    },

    remove (index) {
      this.data6.splice(index, 1)
    },
    elemeterLeft (val) {
      this.elemeter_left = val
      // console.log('val', val)
    },
    getData () {
      let room = this.room
      http.request(this, api.elemeter_info, [room.roomId, room.id], null, (res, err) => {
        if (!res || err) {
          return
        }
        res.roomId = room = this.room.roomId
        res.id = room = this.room.id
        this.elemeter_info = res
        // console.log('elemeter_info', this.elemeter_info)
      })
    }
  },
  computed: {
    Tip () {
      if (this.elemeter_info.hardware_info && this.elemeter_info.hardware_info.sn) {
        const elemeterType = this.elemeter_info.hardware_info.sn.substring(6, 8)
        let str
        if (elemeterType === '01') {
          str = 4.4
        } else if (elemeterType === '02') {
          str = 8.36
        } else {
          str = 14.52
        }
        this.maxPowerValue = str

        return `功率的单位为kw，您可以输入1 ~ ${str}的数字进行功率设置`
      }

      return ''
    },
    isShowTitle () { // 是否展示标题
      if (this.elemeter_info.hardware_info && this.elemeter_info.hardware_info.versions) {
        let result = false
        const { length } = this.versions_keys
        for (let i = 0; i < length; i++) {
          const { key } = this.versions_keys[i]

          const flag = this.elemeter_info.hardware_info.versions[key]
          if (flag && flag !== '') {
            result = true
            break
          }
        }

        return result
      } else {
        return false
      }
    },
    isPayFirst () { // 是否为预付费
      return this.room_info && this.room_info.pay_type === 1
    },
    refresh () {
      return this.$store.state.room.refresh
    },
    permissions () {
      if (localStorage.permission) {
        return JSON.parse(localStorage.permission)
      } else {
        return {}
      }
    },
    isShowMaxPowerBtn () { // 是否展示超功率设置
      const elemeterInfo = this.elemeter_info.hardware_info
      if (elemeterInfo && elemeterInfo.sn) {
        const { sn } = elemeterInfo

        if (sn) {
          const elemeterType = sn.substring(6, 8)
          if (elemeterType === '80' || elemeterType === '05' || elemeterType === '06' || elemeterType === '11' || elemeterType === '12') { // 除AT120、A4 和A4P，其他电表支持超功率设置
            return false
          } else {
            return true
          }
        }
      }

      return false
    },
    isShowZigBee () {
      const elemeterInfo = this.elemeter_info.hardware_info

      if (elemeterInfo && elemeterInfo.sn) {
        const { sn } = elemeterInfo

        if (sn) {
          const elemeterType = sn.substring(6, 8)
          if (elemeterType === '04' || elemeterType === '09' || elemeterType === '13' || elemeterType === '07' || elemeterType === '08') { // ZigBee信息只在 采集器、A1Z、A1PZ、AMC1、AMW1和AMG1显示。
            return true
          } else {
            return false
          }
        }
      }

      return false
    }
  },
  watch: {
    refresh () {
      this.getData()
    }
  },
  filters: {
    dateFrm: function (el) {
      if (el === -1 || !el) {
        return ' - '
      }
      return dayjs(el).format('YYYY-MM-DD HH:mm')
    },
    amountFrm (el) {
      return Number(el).toFixed(2)
    }
  }
}
</script>
<style lang='less' scoped>
@import '../../styles/common.less';
.elemeter {
    &-base {
        background-color: #fff;
        &-row {
            display: flex;
            padding: 10px 0;
            &-item {
                border-right: 1px solid #bbbec4;
                &-line {
                    padding: 15px 0 5px 20px;
                    font-size: 14px;
                    color: #000000;
                }
            }
            &-action {
                padding: 9px 0 5px 20px;
                &-button {
                    width: 100px;
                    margin-right: 5px;
                }
            }
            &-right {
                &-item {
                    border-left: 1px solid #bbbec4;
                }
            }
        }
    }
    .yd-button {
        margin-left: 10px;
    }
}
i{
    font-style: normal
}
</style>